package com.dd.ddapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.dd.ddapiclientsdk.model.User;


import java.util.HashMap;
import java.util.Map;

import static com.dd.ddapiclientsdk.utils.SignUtils.genSign;


//调用第三方接口的客户端
public class DdApiClient {

    private static final String GATEWAY_HOST="http://localhost:8090";
    private String accessKey;
    private String secretKey;

    public DdApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name){
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap=new HashMap<>();
        paramMap.put("name",name);
        String result= HttpUtil.get(GATEWAY_HOST+"/api/name/",paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name){
        HashMap<String, Object> paramMap=new HashMap<>();
        paramMap.put("name",name);
        String result= HttpUtil.post(GATEWAY_HOST+"/api/name/",paramMap);
        System.out.println(result);
        return result;
    }

    private Map<String,String> getHeadersMap(String body){
        Map<String, String> hashMap=new HashMap<>();
        hashMap.put("accessKey",accessKey);
        //秘钥一定不能发送
//        hashMap.put("secretKey",secretKey);
        //设置随机数0~9999
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body",body);
        hashMap.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        hashMap.put("sign", genSign(body,secretKey));//生成签名
        return hashMap;
    }

    //生成签名，放到Utils.SignUtils中去了
//    private String genSign(Map<String, String> hashMap,String secretKey){
//        Digester md5=new Digester(DigestAlgorithm.SHA256);
//        String content=hashMap.toString()+"."+secretKey;
//        return md5.digestHex(content);
//    }

    public String getUsernameByPost(User user){
        String json= JSONUtil.toJsonStr(user);
        HttpResponse httpResponse= HttpRequest.post(GATEWAY_HOST+"/api/name/user")
                .addHeaders(getHeadersMap(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result =httpResponse.body();
        System.out.println(result);
        return result;
    }
}
